package com.jeomo.sys.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.exception.JeomoIllegalStateException;
import com.jeomo.common.core.exception.OperationNotAllowException;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.sys.api.enums.OrgStatusEnum;
import com.jeomo.sys.api.enums.OrgTypeEnum;
import com.jeomo.sys.starter.entity.Org;
import com.jeomo.sys.starter.mapper.OrgMapper;
import com.jeomo.sys.starter.service.IOrgService;
import com.jeomo.sys.starter.util.CommonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * @author 崔贺
 */
@Service
public class OrgServiceImpl extends BaseServiceImpl<OrgMapper, Org> implements IOrgService {

    @Resource
    OrgMapper orgMapper;


    @Override
    public int create(Org org) {
        String recentlyCode = orgMapper.queryRecentlyCode();
        String code;
        if (null != recentlyCode) {
            code = CommonUtil.addOne(recentlyCode);
        } else {
            code = CommonUtil.SERIALS_NUMBER;
        }
        org.setCode(code);
        String topOrgCode = null;
        if (StringUtils.isNotEmpty(org.getParentCode())) {
            Org parentOrg = getById(org.getParentCode());
            if(!parentOrg.isGroup()) {
                throw new OperationNotAllowException("不允许在门店下再新建门店");
            }
            Org hasStopedParent = hasParentStoped(parentOrg);
            if(hasStopedParent != null) {
                throw new OperationNotAllowException(String.format("父节点%s【%s】已被停用，不能新建", hasStopedParent.getCode(), hasStopedParent.getName()));
            }
            topOrgCode = parentOrg.getTopOrgCode();
        }
        org.setTopOrgCode(topOrgCode);
        // 创建组织默认是正常状态
        org.setStatus(OrgStatusEnum.NORMAL);
        return orgMapper.insert(org);
    }

    @Override
    public boolean removeById(Serializable code) {
        Org org = getById(code);
        if (OrgTypeEnum.MALL.equals(org.getType())) {
            return super.removeById(code);
        } else {
            //删除分组， 确保是空的分组才可以删除
            List<Org> malls = listChildren((String) code);
            if (malls.size() > 0) {
                throw new JeomoIllegalStateException("分组下尚有其他组织，不能删除");
            }
            return super.removeById(code);
        }
    }

    @Override
    public boolean updateById(Org entity) {
        //确保，父节点是分组
        Org parent = getById(entity.getParentCode());
        if(parent != null && parent.isMall()) {
            throw new JeomoIllegalStateException("父节点不能是门店");
        }
        Org hasStopedParent = hasParentStoped(parent);
        if(hasStopedParent != null) {
            throw new OperationNotAllowException(String.format("父节点%s【%s】已被停用，不能修改", hasStopedParent.getCode(), hasStopedParent.getName()));
        }
        //如果自己的属性从分组变为门店，要确保没有以自己为父节点的节点
        Org org = getById(entity.getCode());
        if(org.isGroup() && entity.isMall()) {
            List<Org> children = listChildren(org.getCode());
            if(children != null && children.size() > 0) {
                throw new JeomoIllegalStateException("分组下仍有子节点，不能修改属性");
            }
        }
        return super.updateById(entity);
    }

    @Override
    public List<Org> listGroup() {
        return orgMapper.listByType(OrgTypeEnum.MALL_GROUP.getCode());
    }

    @Override
    public List<Org> listChildren(String parentCode) {
        return orgMapper.listChildren(parentCode);
    }

    @Override
    public void stop(String orgCode) {
        Org org = getById(orgCode);
        if(org.isGroup()) {
            List<Org> children = orgMapper.listChildren(orgCode);
            if(children != null) {
                for(Org child : children) {
                    if(OrgStatusEnum.NORMAL.equals(child.getStatus())) {
                        stop(child.getCode());
                    }
                }
            }
        }
        orgMapper.stop(orgCode);
    }


    @Override
    public void start(String orgCode) {
        Org hasStopedParent = findStopedParent(orgCode);
        if(hasStopedParent != null) {
            throw new JeomoIllegalStateException(String.format("尚有父组织【%s】【%s】被停用，请先启用父节点", hasStopedParent.getCode(), hasStopedParent.getName()));
        }
        orgMapper.start(orgCode);
    }

    private Org hasParentStoped(Org parent){
        if(parent.hasStoped()) {
            return parent;
        }
        Org hasStopedParent = findStopedParent(parent.getCode());
        if(hasStopedParent != null) {
            return hasStopedParent;
        }
        return hasStopedParent;
    }

    private Org findStopedParent(String orgCode) {
        Org org = getById(orgCode);
        String parentCode = org.getParentCode();
        while(StringUtils.isNotEmpty(parentCode)) {
            Org parent = getById(parentCode);
            if(parent != null && OrgStatusEnum.HAS_STOP_ED.equals(parent.getStatus())) {
               return parent;
            } else if(parent != null) {
                parentCode = parent.getParentCode();
            } else {
                parentCode = null;
            }
        }
        return null;
    }

}
